package com.version1_1.service.implement;

import com.util.format.MapToJson;
import com.version1_1.model.User;
import com.util.property.Properties;
import com.util.rongcloud.ApiHttpClient;
import com.util.rongcloud.models.ContactNtfMessage;
import com.util.rongcloud.models.FormatType;
import com.version1_1.dao.UserDao;
import com.version1_1.service.RongCloudService;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by reeves on 2015/12/1.
 */

@Service
public class RongCloudServiceImpl implements RongCloudService {

    private static final Logger LOGGER = Logger.getLogger(RongCloudServiceImpl.class);

    @Autowired
    private UserDao userDao;

    /**
     * 调用第三方SDK，融云，得到用户的Token值
     *
     * @param appKey
     * @param appSecret
     * @param userId
     */
    @Override
    @Cacheable(value = {"userTokenVersion1_1"})
    public String getToken(String appKey, String appSecret, int userId) {
        User user = userDao.getUserInfo(userId);
        if (user == null) {
            LOGGER.error("根据userId获取用户对象出错,user is null...");

            // 未登陆用户token值为约定值
            return new MapToJson("token", "null").toJsonString();
        }

        // 判断用户是否已经获取到了token
        if (!user.getTokenRY().isEmpty()) {
            return "{\"token\":\"" + user.getTokenRY() + "\"}";
        } else {
            String tokenStr = "";

            try {
                tokenStr = ApiHttpClient.getToken(Properties.RongCloud_appKey, Properties.RongCloud_appSecret, String.valueOf(userId), user.getUserName(), user.getUserPhoto(), FormatType.json).toString();
            } catch (Exception exception) {
                LOGGER.error("调用融云getToken接口出错...", exception);
            }
            // 更新用户tokenRY的值
            JSONObject getTokenResult = JSONObject.fromObject(tokenStr);
            System.out.println(tokenStr);

            String userToken = "";
            try {
                userToken = (String) getTokenResult.getJSONObject("result").getString("token");

                if ("null".equals(userToken)) {
                    // 融云服务器返回token值为"null"
                    return "{\"token\":\"null\"}";
                }
                userDao.updateUserTokenRY(userId, userToken);
            } catch (JSONException jsonException) {
                // 防止融云服务器json字符串中没有token这个key
                LOGGER.info(jsonException);
            }

            return "{\"token\":\"" + userToken + "\"}";
        }

    }

    /**
     * 根据userId获取用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public String getUserInfo(int userId) {
        User user = userDao.getUserInfo(userId);
        if (user == null) {
            return "{\"code\":0}";
        }

        String userPhoto = "";
        if (user.getUserPhoto() != null) {
            userPhoto = user.getUserPhoto() + Properties.ImageQuality;
        }

        return "{"
                + "\"code\":1" + ","
                + "\"userName\":\"" + user.getUserName() + "\","
                + "\"userPhoto\":\"" + userPhoto
                + "\"}";
    }

    /**
     * 添加好友、同意添加好友，拒绝添加好友
     *
     * @param addFriendsStr
     * @return
     */
    @Override
    public String addFriends(String addFriendsStr) {

        JSONObject addFJsonObject = JSONObject.fromObject(addFriendsStr);
        String fromUserId = addFJsonObject.getString("fromUserId");
        String toUserId = addFJsonObject.getString("toUserId");
        String content = addFJsonObject.getString("content");

        List<String> toUserIds = new ArrayList<>();
        toUserIds.add(toUserId);

        // 调用融云API接口
        try {
            String result = ApiHttpClient.publishSystemMessage(Properties.RongCloud_appKey, Properties.RongCloud_appSecret, fromUserId, toUserIds, new ContactNtfMessage("addFriends", fromUserId, toUserId, content), content, null, FormatType.json).toString();
        } catch (Exception e) {
            LOGGER.error("调用融云API添加好友失败...", e);
            return "{\"addFriendsResult\":false}";
        }
        return "{\"addFriendsResult\":true}";
    }
}
